package person.twj.orderservice.feign.client;

import com.alibaba.fastjson2.JSON;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import person.twj.common.feign.AccountFeignService;
import person.twj.common.feign.OrderFeignService;
import person.twj.orderservice.entity.OrderTbl;
import person.twj.orderservice.service.IOrderTblService;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderFeignServiceImpl implements OrderFeignService {
    @Autowired
    private AccountFeignService accountService;
    @Autowired
    @Qualifier("orderTblServiceImpl")
    private IOrderTblService iOrderTblService;
    @Override
    @GetMapping(value = "/order")
    @GlobalTransactional
    public String order(@RequestParam("userId") String userId,
                        @RequestParam("commodityCode") String commodityCode,
                        @RequestParam("orderCount") int orderCount,
                        @RequestParam("type") int type) {
        log.info("Order Service Begin ... xid: " + RootContext.getXID());

        int orderMoney = calculate(commodityCode, orderCount);


        String rs = accountService.account(userId, orderMoney,type);
        if (!"SUCCESS".equals(rs)) {

//            throw new RuntimeException("错误");
            return "FAIL";
        }

        OrderTbl order = OrderTbl.builder()
                .id(1)
                .userId(userId)
                .money(orderMoney)
                .commodityCode(commodityCode)
                .count(orderCount)
                .build();


        OrderTbl oriOrder = iOrderTblService.getById("1");
        log.info("原始order: " + JSON.toJSONString(oriOrder));

        boolean result = iOrderTblService.updateById(order);
        log.info("Order Service End result: " + result);

        if(type==2){
            throw new RuntimeException("错误");
        }

        if (result) {
            return "SUCCESS";
        }
        return "FAIL";
    }

    private int calculate(String commodityCode, int orderCount) {
        return orderCount * 100;
    }


}
